package com.mayn.jst.login;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mayn.jst.shop.action.ShopAccountAction;
import com.mayn.jst.shop.action.ShopAction;
import com.mayn.jst.shop.model.ShopAccountModel;
import com.mayn.util.CookieUtil;
import com.mayn.util.DateUtil;
import com.mayn.util.DriverFactory;
import com.mayn.util.HttpUtil;
import com.mayn.util.ProcessUtil;
import com.mayn.util.RegUtil;
import com.mayn.util.SendCloudMailUtil;
import com.mayn.util.StringUtil;
import com.mayn.util.WebDriverUtil;
import com.mayn.util.XsoupUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 淘宝后台登录
 * 
 * @author Administrator
 * 
 * 
 */
public class TaobaoLoginAction {
	private static final Logger LOG = LoggerFactory.getLogger(TaobaoLoginAction.class);

	static String loginUrl = "https://login.taobao.com/member/login.jhtml?from=taobaoindex&f=top&style=&sub=true&redirect_url=";

	// 淘宝客登录URL
	static String taobaokeLoginUrl = "https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&from=alimama&redirectURL=http%3A%2F%2Flogin.taobao.com%2Fmember%2Ftaobaoke%2Flogin.htm%3Fis_login%3d1&full_redirect=true&disableQuickLogin=true";

	static String defaultRedirectUrl = "https://mai.taobao.com/seller_admin.htm";

	static int maxWaitTime = 1800000;// 1000 * 60 * 30 = 30 分钟

	/**
	 * 检查指定店铺的cookie是否依然生效
	 * 
	 * @param shopId
	 * @return
	 */
	public static boolean checkAndSaveTaobaoLoginCookie(int shopId) {
		String shopName = ShopAction.getShop(shopId).getStr("SHOP_NAME");
		//查询指定店铺帐号登录的cookie
		String cookie = ShopAccountAction.getShopAccountCookie(shopId);
		//LOG.info("开始检查店铺cookie有效性--" + shopName);
		if (cookie == null || cookie.equals("") || (!checkTaobaoLoginCookie(cookie))) {
			LOG.info("当前店铺cookie已失效，需重新获取--" + shopName);
			cookie = getTaobaoLoginCookieStr(shopId);
			if (checkTaobaoLoginCookie(cookie)) {
				ShopAccountAction.saveShopAccountCookie(shopId, cookie, 1);
				LOG.info("当前店铺cookie重新获取成功--" + shopName);
				return true;
			} else {
				LOG.error("当前店铺cookie重新获取失败--" + shopName);
				ShopAccountAction.saveShopAccountCookie(shopId, cookie, 2);
			}
		} else {
			//LOG.info("当前店铺cookie依然有效--" + shopName);
			return true;
		}
		return false;
	}

	/**
	 * 不检查cookie重新登陆
	 * 
	 * @param shopId
	 * @return
	 */
	public static boolean ForceSaveTaobaoLoginCookie(int shopId) {
		String cookie = getTaobaoLoginCookieStr(shopId);
		ShopAccountAction.saveShopAccountCookie(shopId, cookie, 1);
		return false;
	}

	/**
	 * 检查淘宝cookie是否有效
	 * 
	 * @param cookie
	 * @return
	 */
	public static Boolean checkTaobaoLoginCookie(String cookie) {
		if (checkDsrCookie(cookie) && checkSubWayCookie(cookie) && checkZuanshiCookie(cookie)) {
			return true;
		}
		return false;
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static JSONObject getTaobaoLoginCookieObj(int shopId) {
		JSONObject dataJson = new JSONObject();
		String cookieStr = HttpUtil.getCookieStr(getTaobaoLoginCookie(shopId));
		if (cookieStr == null || cookieStr.equals("")) {
			dataJson.put("Success", false);
			dataJson.put("Data", "");
		} else {
			dataJson.put("Success", true);
			dataJson.put("Data", cookieStr);
		}
		return dataJson;
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static String getTaobaoLoginCookieStr(int shopId) {
		return HttpUtil.getCookieStr(getTaobaoLoginCookie(shopId));
	}

	public static String getTaobaoLoginCookieStr(int shopId, String redirect_url) {
		return HttpUtil.getCookieStr(getTaobaoLoginCookie(shopId, redirect_url,null));
	}
	
	public static String getTaobaoLoginCookieStr(int shopId, String redirect_url, String jumpUrl) {
		return HttpUtil.getCookieStr(getTaobaoLoginCookie(shopId, redirect_url,jumpUrl));
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param userName
	 * @param userPass
	 * @param redirect_url
	 * @return
	 */
	public static String getTaobaoLoginCookieStr(String shopName, String userName, String userPass, String redirect_url) {
		return HttpUtil.getCookieStr(getTaobaoLoginCookie(shopName, userName, userPass, redirect_url));
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param userName
	 * @param userPass
	 * @param redirect_url
	 * @param jumpUrl
	 * @return
	 */
	public static String getTaobaoLoginCookieStr(String shopName, String userName, String userPass, String redirect_url, String jumpUrl) {
		return HttpUtil.getCookieStr(getTaobaoLoginCookie(userName, userPass, redirect_url, jumpUrl));
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static Set<Cookie> getTaobaoLoginCookie(int shopId) {
		return getTaobaoLoginCookie(shopId, defaultRedirectUrl,null);
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param shopId
	 * @param redirect_url
	 * @return
	 */
	public static Set<Cookie> getTaobaoLoginCookie(int shopId, String redirect_url, String jumpUrl) {
		String userName = "";
		String userPass = "";
		String shopName = "";
		if (shopId > 0) {
			ShopAccountModel shopAccount = ShopAccountAction.getShopAccount(shopId);
			if (shopAccount != null) {
				userName = shopAccount.getStr("SA_SHOP_USERNAME");
				userPass = shopAccount.getStr("SA_SHOP_USERPASS");
				shopName = shopAccount.getStr("SHOP_NAME");
			}
		} else {
			LOG.error("shopId参数错误:" + shopId);
			return null;
		}
		return getTaobaoLoginCookie(shopName, userName, userPass, redirect_url,jumpUrl);
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param userName
	 * @param userPass
	 * @param redirect_url
	 * @return
	 */
	public static Set<Cookie> getTaobaoLoginCookie(String shopName, String userName, String userPass, String redirect_url) {
		return getTaobaoLoginCookie(shopName, userName, userPass, redirect_url, null);
	}

	/**
	 * 登陆淘宝获取cookie
	 * 
	 * @param userName
	 * @param userPass
	 * @param redirect_url
	 * @param jumpUrl
	 * @return
	 */
	public static Set<Cookie> getTaobaoLoginCookie(String shopName, String userName, String userPass, String redirect_url, String jumpUrl) {
		if (redirect_url == null) {
			redirect_url = defaultRedirectUrl;
		}
		Set<Cookie> cookieSet = null;
		WebDriver driver = null;
		try {
			ChromeOptions options = new ChromeOptions();
			// 设置user agent为iphone5
			options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			driver = DriverFactory.getWebDriver(options);
			// 清理cookie
			if (driver != null) {
				driver.manage().deleteAllCookies();
			}

			// 浏览器窗口最大化
			driver.manage().window().maximize();

			/**
			 * 如果需要执行js，参考 String js =
			 * "document.getElementById('J_LoginBox').setAttribute('class','login-box no-longlogin module-static');return document.getElementById('J_LoginBox').className;"
			 * ; String
			 * ret=(String)((JavascriptExecutor)driver).executeScript(js);
			 * LOG.info(ret);
			 */
			if (loginUrl.endsWith("=")) {
				loginUrl = loginUrl + redirect_url;
			}
			driver.get(loginUrl);
			By by = null;

			String title = driver.getTitle();
			LOG.info(title);

			// LOG.info(driver.getPageSource());

			// 模拟鼠标操作
			ProcessUtil.ThreadSleep(1024);
			String xpath = "//div[@class='login-adlink']";
			Actions action = new Actions(driver);
			action.moveToElement(driver.findElement(By.xpath(xpath)));
			ProcessUtil.ThreadSleep(1024);
			action.perform();
			ProcessUtil.ThreadSleep(1024);
			action.moveToElement(driver.findElement(By.id("J_Quick2Static")));
			ProcessUtil.ThreadSleep(1024);
			action.perform();
			ProcessUtil.ThreadSleep(1024);

			WebElement loginBox = driver.findElement(By.id("J_LoginBox"));
			if (loginBox != null) {
				if (!loginBox.getAttribute("class").contains("module-static")) {
					WebElement J_Quick2Static = driver.findElement(By.id("J_Quick2Static"));
					if (J_Quick2Static != null) {
						WebDriverUtil.waitUntilVisible(driver, J_Quick2Static);
						J_Quick2Static.click();
					}
				}
			}

			ProcessUtil.ThreadSleep(1024);
			by = By.xpath("//input[@name='TPL_username']");
			WebElement user = driver.findElement(by);
			if (user != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
				user.clear();
				char[] charArray = userName.toCharArray();
				for (int i = 0; i < charArray.length; i++) {
					user.sendKeys(charArray[i] + "");
					int temp = (int) (600 * Math.random() + 1800);
					ProcessUtil.ThreadSleep(temp);
				}
				// user.sendKeys(userName);
			}

			ProcessUtil.ThreadSleep(3000);
			by = By.xpath("//input[@name='TPL_password']");
			WebElement password = driver.findElement(by);
			if (password != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
				password.clear();
				password.sendKeys(userPass);
			}

			ProcessUtil.ThreadSleep(800);
			by = By.id("J_SubmitStatic");
			WebElement submit = driver.findElement(by);
			if (submit != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
			}
			ProcessUtil.ThreadSleep(500);
			LOG.debug(driver.getCurrentUrl());
			int sleepMs = 0;
			int sendTimes = 0;
			boolean sendErr = false;
			boolean retry = false;
			while (true) {
				if (HttpUtil.getHost(driver.getCurrentUrl()).equals("login.taobao.com")) {
					by = By.id("nocaptcha");
					WebElement noCaptcha = null;
					try {
						noCaptcha = driver.findElement(by);
					} catch (Exception e) {

					}
					if (noCaptcha != null) {
						if (noCaptcha.getAttribute("style").contains("block;")) {
							// 邮件只发送一次
							if (sendTimes == 0) {
								String msg = shopName + "--淘宝登陆需要滑块验证,需要人工干预--" + driver.getCurrentUrl();
								LOG.info(msg);
								SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
								sendErr = true;
							}
							sendTimes = sendTimes + 1;
							ProcessUtil.ThreadSleep(30000);
							driver.get(loginUrl);
							retry = true;
						} else {
							retry = false;
						}
					}
					if (retry) {
						loginBox = driver.findElement(By.id("J_LoginBox"));
						if (loginBox != null) {
							if (!loginBox.getAttribute("class").contains("module-static")) {
								WebElement J_Quick2Static = driver.findElement(By.id("J_Quick2Static"));
								if (J_Quick2Static != null) {
									WebDriverUtil.waitUntilVisible(driver, J_Quick2Static);
									J_Quick2Static.click();
								}
							}
						}
						ProcessUtil.ThreadSleep(1024);
					}
					if (driver.getCurrentUrl().contains("sale.tmall.com")) {
						loginBox = driver.findElement(By.id("J_LoginBox"));
						if (loginBox != null) {
							if (!loginBox.getAttribute("class").contains("module-static")) {
								WebElement J_Quick2Static = driver.findElement(By.id("J_Quick2Static"));
								if (J_Quick2Static != null) {
									WebDriverUtil.waitUntilVisible(driver, J_Quick2Static);
									J_Quick2Static.click();
								}
							}
						}
						ProcessUtil.ThreadSleep(1024);
						by = By.xpath("//input[@name='TPL_username']");
						user = driver.findElement(by);
						if (user != null) {
							WebDriverUtil.moveToElementAndClick(driver, by);
							user.clear();
							user.sendKeys(userName);
						}

						ProcessUtil.ThreadSleep(3000);
						by = By.xpath("//input[@name='TPL_password']");
						password = driver.findElement(by);
						if (password != null) {
							WebDriverUtil.moveToElementAndClick(driver, by);
							password.clear();
							password.sendKeys(userPass);
						}
						ProcessUtil.ThreadSleep(800);
						by = By.id("J_SubmitStatic");
						submit = driver.findElement(by);
						if (submit != null) {
							WebDriverUtil.moveToElementAndClick(driver, by);
						}
						ProcessUtil.ThreadSleep(500);
					}
					sleepMs += 1000;
					LOG.info("还未登录成功,等待10000ms --" + driver.getCurrentUrl());
					ProcessUtil.ThreadSleep(10000);
					// 等待人工登录干预
					if (sleepMs == 1000 * 60 * 3) {
						String msg = shopName + "--淘宝登陆不成功,需要人工干预--" + driver.getCurrentUrl();
						LOG.info(msg);
						if (!sendErr) {
							SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
						}
					}
					if (sleepMs >= maxWaitTime) {
						String msg = shopName + "--淘宝登陆不成功,已等待" + maxWaitTime + "毫秒,退出运行 --" + driver.getCurrentUrl();
						LOG.info(msg);
						SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
						break;
					}
				} else {
					if (HttpUtil.getHost(driver.getCurrentUrl()).equals(HttpUtil.getHost(redirect_url))) {
						break;
					} else {
						driver.get(redirect_url);
						if (HttpUtil.getHost(driver.getCurrentUrl()).equals(HttpUtil.getHost(redirect_url))) {
							break;
						}
					}
				}
			}
			LOG.info(shopName + "--登录成功--" + driver.getCurrentUrl());
			// 登陆需要的页面
			ProcessUtil.ThreadSleep(600);
			
			/*
			driver.get("https://zuanshi.taobao.com/indexbp.html");
			ProcessUtil.ThreadSleep(600);
			driver.get("https://branding.taobao.com/#!/report/index");
			ProcessUtil.ThreadSleep(600);
			
			driver.get("https://rate.taobao.com/ecrm/reviewStat.htm");
			ProcessUtil.ThreadSleep(600);
			driver.get("https://sycm.taobao.com/portal/home.htm");
			*/
			driver.get("https://subway.simba.taobao.com/#!/home");
			ProcessUtil.ThreadSleep(600);

			// 淘宝客无法通过此方法登录
			// driver.get("http://ad.alimama.com/index.htm");
			// driver.get("http://ad.alimama.com/myunion.htm");
			//ProcessUtil.ThreadSleep(2000);
			if (jumpUrl != null) {
				ProcessUtil.ThreadSleep(800);
				driver.get(jumpUrl);
			}
			ProcessUtil.ThreadSleep(2000);
			cookieSet = driver.manage().getCookies();
			for (Cookie ck : cookieSet) {
				LOG.debug(ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure());
			}
		} catch (

		Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null) {
				driver.quit();
			}
		}
		return cookieSet;
	}
	/*----------淘宝后台网页访问---------------------------------------------------------*/

	/**
	 * 检查dsr页面
	 * 
	 * @param cookie
	 * @return
	 */
	public static Boolean checkDsrCookie(String cookie) {
		int pageSize = 10;
		int currentPage = 1;
		try {
			String str = getDsrString(pageSize, currentPage, cookie);
			JSONObject jo = JSONObject.fromObject(str);
			if (jo.containsKey("success")) {
				if (jo.getBoolean("success")) {
					LOG.debug("Dsr Data Success=" + jo.getBoolean("success"));
					return true;
				}
			}
			return false;
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return false;
		}
	}

	/**
	 * 登陆淘宝获取DSR数据
	 * 
	 * @param cookie
	 * @return
	 */
	public static JSONArray getDsrJsonArray(String cookie) {

		JSONArray dataArray = new JSONArray();

		int pageSize = 500;
		int currentPage = 1;

		int totalPage = 0;
		int totalSize = 0;
		String ret = getDsrString(pageSize, currentPage, cookie);
		if (!ret.equals("{}")) {
			JSONObject fjo = JSONObject.fromObject(ret);
			if (fjo.containsKey("result")) {
				if (fjo.getJSONObject("result").containsKey("totalPage")) {
					totalPage = fjo.getJSONObject("result").getInt("totalPage");
					totalSize = fjo.getJSONObject("result").getInt("totalSize");

					JSONArray ja = fjo.getJSONObject("result").getJSONArray("data");
					for (int i = 0; i < ja.size(); i++) {
						dataArray.add(ja.get(i));
					}

					if (totalPage > 1) {
						for (int i = 2; i <= totalPage; i++) {
							ret = getDsrString(pageSize, i, cookie);
							fjo = JSONObject.fromObject(ret);
							if (fjo.getJSONObject("result").containsKey("data")) {
								ja = fjo.getJSONObject("result").getJSONArray("data");
								for (int j = 0; j < ja.size(); j++) {
									dataArray.add(ja.get(j));
								}
							}
						}
					}
				}
			}
		}
		LOG.info("共有商品" + dataArray.size() + "" + "--" + totalSize + "个");
		return dataArray;

	}

	/**
	 * 登陆淘宝获取DSR数据
	 * 
	 * @param pageSize
	 * @param currentPage
	 * @param cookie
	 * @return
	 */
	public static String getDsrString(int pageSize, int currentPage, String cookie) {

		try {
			String _tb_token_ = "";
			Cookie[] cookieArray = CookieUtil.getCookieByStr(cookie);
			if (cookieArray.length > 0) {
				_tb_token_ = CookieUtil.getCookieByName(cookieArray, "_tb_token_");
			} else {
				LOG.error("Cookie异常");
				return "{}";
			}

			String url = "https://ecrm.taobao.com/itemreview/queryItemReview.do";
			
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept", "*/*");
			headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("referer", "https://rate.taobao.com/ecrm/reviewStat.htm");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3050.3 Safari/537.36");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"cna=UQVMD1i+EFMCAT23zfXiI0x7; thw=cn; _tb_token_=X0M84AH2cnr7P51; ali_ab=61.183.205.245.1464571244928.8; isg=24391109A0B512131BDB6923AC52E373; x=595397331; uc3=nk2=&id2=&lg2=; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E9%AB%98%E6%9F%94; skt=833e268295117448; v=0; cookie2=2c61331f100071c7769b4e9f210ee00a; unb=1761519038; t=fc9e81ac084f9dca32d8657cd26012ba; uc1=cookie14=UoWxNeYRgaDUgQ%3D%3D; l=AqOjlKnJwiQWkXtDjDU4f0qkM-lN0jfa");
			} else {
				headers.put("Cookie", cookie);
			}
			
			
			long ks = DateUtil.getUnixTime();
			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("appId", "10005");
			params.put("reviewType", "1");
			params.put("dateType", "7");
			params.put("currentPage", String.valueOf(currentPage));
			params.put("pageSize", String.valueOf(pageSize));
			params.put("itemId", "");
			params.put("startDate", "");
			params.put("endDate", "");
			params.put("startDsr", "");
			params.put("endDsr", "");
			params.put("_tb_token_", _tb_token_);
			params.put("callback", "reqwest_" + String.valueOf(ks));
			
			

			String resp = "";
			resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
			LOG.debug(resp.trim());
			if (resp.trim().startsWith("reqwest")) {
				if (resp.contains("获取用户信息异常")) {
					LOG.error("获取用户信息异常");
				}
				if (resp.contains("安全校验不通过")) {
					LOG.error("安全校验不通过");
				}
				String regex = "(?:reqwest[\\s\\S]*?\\()([\\s\\S]*)(?:\\))";
				resp = RegUtil.GetRegStr(resp, regex, 1);
			} else {
				resp = "{}";
			}
			return resp;
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
			return "{}";
		}
	}

	/**
	 * 检查直通车cookie是否失效
	 * 
	 * @return
	 */
	public static Boolean checkSubWayCookie(String cookie) {
		try {
			String token = getSubWayToken(cookie);
			if (token.length() > 0) {
				LOG.debug("直通车token=" + token);
				return true;
			} else {
				LOG.error("直通车cookie已失效");
				return false;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return false;
		}
	}

	/**
	 * 获取店铺直通车指定时间段消费情况
	 * 
	 * @param startDate
	 * @param shopId
	 * @return
	 */
	public static Double getSubWayFeeValue(String startDate, int shopId) {
		return getSubWayFeeValue(startDate, startDate, shopId);
	}

	/**
	 * 获取店铺直通车指定时间段消费情况
	 * 
	 * @param startDate
	 * @param endDate
	 * @param shopId
	 * @return
	 */
	public static Double getSubWayFeeValue(String startDate, String endDate, int shopId) {
		// 检查cookie
		if (checkAndSaveTaobaoLoginCookie(shopId)) {
			String cookie = ShopAccountAction.getShopAccountCookie(shopId);
			return getSubWayFeeValue(startDate, endDate, cookie);
		} else {
			return 0D;
		}
	}

	/**
	 * 获取直通车指定时间段消费情况
	 * 
	 * @param startDate
	 * @param endDate
	 * @param cookie
	 * @return
	 */
	public static Double getSubWayFeeValue(String startDate, String endDate, String cookie) {
		Double value = 0D;
		try {
			String str = getSubWayFeeString(startDate, endDate, cookie);
			JSONObject object = JSONObject.fromObject(str);
			if (object.containsKey("result") && object.getJSONObject("result").containsKey("list")) {
				JSONArray array = object.getJSONObject("result").getJSONArray("list");
				if (array.size() > 0) {
					if (array.getJSONObject(0).containsKey("cost")) {
						value = array.getJSONObject(0).getDouble("cost");
						value = value / 100;
					}
				}
			}
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
		}
		return value;
	}

	/**
	 * 获取直通车指定时间段消费情况
	 * 
	 * @param startDate
	 * @param endDate
	 * @param cookie
	 * @return
	 */
	public static String getSubWayFeeString(String startDate, String endDate, String cookie) {
		String resp = "";
		try {
			String token = "";
			token = getSubWayToken(cookie);

			// 第二步，抓取直通车报表中指定日期数据
			String url = "https://subway.simba.taobao.com/report/rptBpp4pCustomSum.htm?startDate=" + startDate + "&endDate=" + endDate + "&effect=-1";

			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept-Encoding", "gzip, deflate, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
			headers.put("Accept-Language", "en-us,en");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
			} else {
				headers.put("Cookie", cookie);
			}
			headers.put("pragma", "no-cache");
			headers.put("referer", "https://subway.simba.taobao.com/");
			headers.put("x-requested-with", "XMLHttpRequest");
			headers.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");

			resp = HttpUtil.sendGetWithURLConnection(url, null, headers);

			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("sla", "json");
			params.put("isAjaxRequest", "true");
			params.put("token", token);
			params.put("_referer", "/report/bpreport/index");

			resp = HttpUtil.sendPostWithURLConnection(url, params, headers);
			LOG.debug(resp.trim());
			if (resp.trim().startsWith("{")) {
				return resp.trim();
			} else {
				resp = "{}";
			}
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
			return "{}";
		}
		return resp;
	}

	/**
	 * 直通车页面Token值获取
	 * 
	 * @param cookie
	 * @return
	 */
	public static String getSubWayToken(String cookie) {
		String token = "";
		String resp = "";
		try {
			// 第一步 获取token值
			String url = "https://subway.simba.taobao.com/bpenv/getLoginUserInfo.htm";
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept-Encoding", "gzip, deflate, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
			headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
			} else {
				headers.put("Cookie", cookie);
			}
			headers.put("referer", "https://subway.simba.taobao.com/");
			headers.put("x-requested-with", "XMLHttpRequest");
			headers.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
	
			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("_referer", "/home");
			resp = HttpUtil.sendPostWithURLConnection(url, params, headers);
			JSONObject object = JSONObject.fromObject(resp.trim());
			
			if (object.containsKey("result") && object.getJSONObject("result").containsKey("token")) {
				token = object.getJSONObject("result").getString("token");
			}else{
				LOG.error("直通车token获取失败" + resp);
			}
			
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
			return "{}";
		}
		return token;
	}

	public static Boolean checkZuanshiCookie(String cookie) {
		try {
			HashMap<String, String> info = TaobaoLoginAction.getZuanshiWebPageInfo(cookie);
			String csrfID = info.get("csrfID");
			String rptToken = info.get("rptToken");
			if (csrfID.length() > 0 && rptToken.length() > 0) {
				LOG.debug("csrfID=" + csrfID + "/rptToken=" + rptToken);
				return true;
			} else {
				LOG.error("钻石展位cookie已失效");
				return false;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return false;
		}
	}

	/**
	 * 钻石展位页面info值获取
	 * 
	 * @param cookie
	 * @return
	 */
	public static HashMap<String, String> getZuanshiWebPageInfo(String cookie) {
		HashMap<String, String> info = new HashMap<String, String>();
		String csrfID = "";
		String rptToken = "";
		int callbackValue = 209;
		try {
			String url = "https://zuanshi.taobao.com/loginUser/info.json";
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept-Encoding", "gzip, deflate, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
			} else {
				headers.put("Cookie", cookie);
			}
			headers.put("referer", "https://zuanshi.taobao.com/indexbp.html");
			headers.put("x-requested-with", "XMLHttpRequest");
			headers.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");

			long ks = DateUtil.getUnixTime();
			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("_ksTS", String.valueOf(ks) + "_" + String.valueOf(callbackValue - 1));
			params.put("callback", "jsonp" + String.valueOf(callbackValue));

			String resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
			if (resp.trim().startsWith("jsonp" + String.valueOf(callbackValue))) {
				String regex = "(?:jsonp" + String.valueOf(callbackValue) + "[\\s\\S]*?\\()([\\s\\S]*)(?:\\))";
				resp = RegUtil.GetRegStr(resp, regex, 1);
				if (resp.startsWith("{")) {
					// LOG.debug(resp);
					JSONObject object = JSONObject.fromObject(resp);
					if (object.containsKey("data") && object.getJSONObject("data").containsKey("csrfID") && object.getJSONObject("data").containsKey("rptToken")) {
						csrfID = object.getJSONObject("data").getString("csrfID");
						rptToken = object.getJSONObject("data").getString("rptToken");
						info.put("csrfID", csrfID);
						info.put("rptToken", rptToken);
						return info;
					}
				}
			}
			LOG.error("info获取失败--" + resp);
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
		}
		return info;
	}

	/**
	 * 获取钻石展位费用
	 * 
	 * @param startDate
	 * @param shopId
	 * @return
	 */
	public static Double getZuanshiFeeValue(String startDate, int shopId) {
		// 检查cookie
		if (checkAndSaveTaobaoLoginCookie(shopId)) {
			String cookie = ShopAccountAction.getShopAccountCookie(shopId);
			return getZuanshiFeeValue(startDate, startDate, cookie);
		} else {
			return 0D;
		}

	}

	/**
	 * 获取钻石展位费用
	 * 
	 * @param startDate
	 * @param cookie
	 * @return
	 */
	public static Double getZuanshiFeeValue(String startDate, String cookie) {
		return getZuanshiFeeValue(startDate, startDate, cookie);
	}

	/**
	 * 获取钻石展位费用
	 * 
	 * @param startDate
	 * @param endDate
	 * @param cookie
	 * @return
	 */
	public static Double getZuanshiFeeValue(String startDate, String endDate, String cookie) {
		double charge = 0D;
		String resp = "";
		int callbackValue = 47420;
		try {
			// 第一步，获取csrfIDrptToken
			HashMap<String, String> info = TaobaoLoginAction.getZuanshiWebPageInfo(cookie);
			String csrfID = info.get("csrfID");
			String rptToken = info.get("rptToken");
			long ks = DateUtil.getUnixTime();
			// 第二步
			String url = "https://report.simba.taobao.com/common/query/zszw/1/rptAdvertiser.json";
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			headers.put("Accept", "*/*");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
			} else {
				headers.put("Cookie", cookie);
			}
			headers.put("cache-control", "no-cache");
			headers.put("pragma", "no-cache");
			headers.put("referer", "https://zuanshi.taobao.com/indexbp.html");

			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("csrfID", csrfID);
			params.put("_ksTS", String.valueOf(ks) + "_" + String.valueOf(callbackValue - 1));
			params.put("callback", "jsonp" + String.valueOf(callbackValue));
			params.put("token", URLEncoder.encode(rptToken, "UTF-8"));
			params.put("effectType", "impression");
			params.put("effect", "7");
			params.put("startTime", startDate);
			params.put("endTime", endDate);
			long t = DateUtil.getUnixTime();
			params.put("t", String.valueOf(t));

			resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
			if (resp.trim().startsWith("jsonp" + String.valueOf(callbackValue))) {
				String regex = "(?:jsonp" + String.valueOf(callbackValue) + "[\\s\\S]*?\\()([\\s\\S]*)(?:\\))";
				resp = RegUtil.GetRegStr(resp, regex, 1);
				if (resp.startsWith("{")) {
					JSONObject object = JSONObject.fromObject(resp);
					if (object.containsKey("data")) {
						if (object.getJSONObject("data").containsKey("result")) {
							if (object.getJSONObject("data").getJSONArray("result").size() > 0) {
								if (object.getJSONObject("data").getJSONArray("result").getJSONObject(0).containsKey("charge")) {
									charge = object.getJSONObject("data").getJSONArray("result").getJSONObject(0).getDouble("charge");
									return charge;
								}
							} else {
								return charge;
							}
						}
					}
				}
			}
			LOG.error("info获取失败--" + resp);
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
		}
		return charge;
	}

	/**
	 * 品销宝页面token
	 * 
	 * @param cookie
	 * @return
	 */
	public static String getBrandingToken(String cookie) {
		String token = "";
		try {
			String url = "https://branding.taobao.com/report/getToken.json";
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept-Encoding", "gzip, deflate, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
			} else {
				headers.put("Cookie", cookie);
			}
			headers.put("referer", "https://branding.taobao.com/");
			headers.put("x-requested-with", "XMLHttpRequest");
			headers.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");

			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			long t = DateUtil.getUnixTime();
			params.put("t", String.valueOf(t));

			String resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
			if (resp.startsWith("{")) {
				JSONObject object = JSONObject.fromObject(resp);
				if (object.containsKey("data") && object.getJSONObject("data").containsKey("token")) {
					token = object.getJSONObject("data").getString("token");
					return token;
				}
			}
			LOG.error("token获取失败--" + resp);
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
		}
		return token;
	}

	/**
	 * 品销宝费用
	 * 
	 * @param startDate
	 * @param shopId
	 * @return
	 */
	public static Double getBrandingFeeValue(String startDate, int shopId) {
		// 检查cookie
		if (checkAndSaveTaobaoLoginCookie(shopId)) {
			String cookie = ShopAccountAction.getShopAccountCookie(shopId);
			return getBrandingFeeValue(startDate, startDate, cookie);
		} else {
			return 0D;
		}

	}

	/**
	 * 品销宝费用
	 * 
	 * @param startDate
	 * @param cookie
	 * @return
	 */
	public static Double getBrandingFeeValue(String startDate, String cookie) {
		return getBrandingFeeValue(startDate, startDate, cookie);
	}

	/**
	 * 品销宝费用
	 * 
	 * @param cookie
	 * @return
	 */
	public static Double getBrandingFeeValue(String startDate, String endDate, String cookie) {
		Double cost = 0D;
		int callbackValue = 5456;
		try {
			// 第一步获取token
			String token = TaobaoLoginAction.getBrandingToken(cookie);
			long ks = DateUtil.getUnixTime();
			// 第二步
			String url = "https://report.simba.taobao.com/common/queryhllc/brand/1/rptAdvertiserSubList.json";
			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept-Encoding", "gzip, deflate, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
			if (cookie == null || cookie.trim().equals("")) {
				headers.put("Cookie",
						"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
			} else {
				headers.put("Cookie", cookie);
			}
			headers.put("referer", "https://branding.taobao.com/");

			LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			params.put("startdate", startDate);
			params.put("enddate", endDate);
			params.put("effect", "15");
			params.put("productid", "101005202");
			params.put("groupby", "memberid");
			params.put("_ksTS", String.valueOf(ks) + "_" + String.valueOf(callbackValue - 1));
			params.put("callback", "jsonp" + String.valueOf(callbackValue));
			params.put("token", URLEncoder.encode(token, "UTF-8"));

			String resp = HttpUtil.sendGetWithURLConnection(url, params, headers);
			if (resp.trim().startsWith("jsonp" + String.valueOf(callbackValue))) {
				String regex = "(?:jsonp" + String.valueOf(callbackValue) + "[\\s\\S]*?\\()([\\s\\S]*)(?:\\))";
				resp = RegUtil.GetRegStr(resp, regex, 1);
				if (resp.startsWith("{")) {
					JSONObject object = JSONObject.fromObject(resp);
					if (object.containsKey("data")) {
						if (object.getJSONObject("data").containsKey("result")) {
							if (object.getJSONObject("data").getJSONArray("result").getJSONObject(0).containsKey("cost")) {
								cost = object.getJSONObject("data").getJSONArray("result").getJSONObject(0).getDouble("cost");
								// 特殊处理
								cost = cost / 100;
								return cost;
							}
						} else {
							// 部分日期品销宝费用为0
							if (object.containsKey("info") && object.getJSONObject("info").containsKey("errorCode")) {
								if (object.getJSONObject("info").getString("errorCode").equals("200")) {
									return cost;
								}
							}
						}
					}
				}
			}
			LOG.error("getBrandingFeeValue Error--" + resp);
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
		}
		return cost;
	}

	/** ---淘宝客数据抓取--- */

	/**
	 * 获取阿里妈妈登录cookie,失效则重新登录
	 * 
	 * @param shopId
	 * @return
	 */
	public static String checkAndGetAlimamaLoginCookie(int shopId) {

		String shopName = ShopAction.getShop(shopId).getStr("SHOP_NAME");
		String cookie = ShopAccountAction.getShopAccountAlimamaCookie(shopId);

		LOG.info("开始检查店铺cookie有效性--" + shopName);
		if (cookie == null || cookie.equals("") || (!checkAlimamaLoginCookie(cookie))) {
			LOG.info("当前店铺cookie已失效，需重新获取--" + shopName);
			cookie = getAlimamaLoginCookieStr(shopId);
			if (checkAlimamaLoginCookie(cookie)) {
				ShopAccountAction.saveShopAccountAlimamaCookie(shopId, cookie, 1);
				LOG.info("当前店铺cookie重新获取成功--" + shopName);
				return cookie;
			} else {
				LOG.error("当前店铺cookie重新获取失败--" + shopName);
				ShopAccountAction.saveShopAccountAlimamaCookie(shopId, cookie, 2);
			}
		} else {
			LOG.info("当前店铺cookie依然有效--" + shopName);
			return cookie;
		}
		return "";

	}

	/**
	 * 检测阿里妈妈cookie是否失效
	 */
	private static boolean checkAlimamaLoginCookie(String cookie) {
		String token = TaobaoLoginAction.getMyunionTbToken(cookie);
		if (StringUtil.isBlank(token)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 淘宝客登录获取cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static String getAlimamaLoginCookieStr(int shopId) {
		return HttpUtil.getCookieStr(getAlimamaLoginCookie(shopId));
	}

	/**
	 * 淘宝客登录获取cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static Set<Cookie> getAlimamaLoginCookie(int shopId) {
		String userName = "";
		String userPass = "";
		String shopName = "";
		if (shopId > 0) {
			ShopAccountModel shopAccount = ShopAccountAction.getShopAccount(shopId);
			if (shopAccount != null) {
				userName = shopAccount.getStr("SA_SHOP_USERNAME");
				userPass = shopAccount.getStr("SA_SHOP_USERPASS");
				shopName = shopAccount.getStr("SHOP_NAME");
			}
		} else {
			LOG.error("shopId参数错误:" + shopId);
			return null;
		}
		return getAlimamaLoginCookie(taobaokeLoginUrl, shopName, userName, userPass);
	}

	/**
	 * 淘宝客登录获取cookie
	 * 
	 * @param shopName
	 * @param loginUrl
	 * @param userName
	 * @param userPass
	 * @return
	 */
	public static Set<Cookie> getAlimamaLoginCookie(String loginUrl, String shopName, String userName, String userPass) {
		String redirect_url = "https://ad.alimama.com/myunion.htm";

		Set<Cookie> cookieSet = null;
		WebDriver driver = null;
		try {
			ChromeOptions options = new ChromeOptions();
			// 设置user agent为iphone5
			options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			driver = DriverFactory.getWebDriver(options);
			// 清理cookie
			if (driver != null) {
				driver.manage().deleteAllCookies();
			}
			// 浏览器窗口最大化
			driver.manage().window().maximize();

			driver.get(loginUrl);
			By by = null;

			String title = driver.getTitle();
			LOG.info(title);

			// 模拟鼠标操作

			Actions action = new Actions(driver);
			ProcessUtil.ThreadSleep(1024);
			action.moveToElement(driver.findElement(By.id("J_Quick2Static")));
			ProcessUtil.ThreadSleep(1024);
			action.perform();
			ProcessUtil.ThreadSleep(1024);

			WebElement loginBox = driver.findElement(By.id("J_LoginBox"));
			if (loginBox != null) {
				if (!loginBox.getAttribute("class").contains("module-static")) {
					WebElement J_Quick2Static = driver.findElement(By.id("J_Quick2Static"));
					if (J_Quick2Static != null) {
						WebDriverUtil.waitUntilVisible(driver, J_Quick2Static);
						J_Quick2Static.click();
					}
				}
			}

			ProcessUtil.ThreadSleep(1024);
			by = By.xpath("//input[@name='TPL_username']");
			WebElement user = driver.findElement(by);
			if (user != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
				user.clear();
				char[] charArray = userName.toCharArray();
				for (int i = 0; i < charArray.length; i++) {
					user.sendKeys(charArray[i] + "");
					int temp = (int) (600 * Math.random() + 1800);
					ProcessUtil.ThreadSleep(temp);
				}
				// user.sendKeys(userName);
			}

			ProcessUtil.ThreadSleep(3000);
			by = By.xpath("//input[@name='TPL_password']");
			WebElement password = driver.findElement(by);
			if (password != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
				password.clear();
				password.sendKeys(userPass);
			}

			ProcessUtil.ThreadSleep(800);
			by = By.id("J_SubmitStatic");
			WebElement submit = driver.findElement(by);
			if (submit != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
			}
			ProcessUtil.ThreadSleep(500);
			LOG.debug(driver.getCurrentUrl());
			int sleepMs = 0;
			@SuppressWarnings("unused")
			int sendTimes = 0;
			boolean sendErr = false;
			@SuppressWarnings("unused")
			boolean retry = false;
			while (true) {
				if (driver.getCurrentUrl().contains("login")) {
					loginBox = driver.findElement(By.id("J_LoginBox"));
					if (loginBox != null) {
						if (!loginBox.getAttribute("class").contains("module-static")) {
							WebElement J_Quick2Static = driver.findElement(By.id("J_Quick2Static"));
							if (J_Quick2Static != null) {
								WebDriverUtil.waitUntilVisible(driver, J_Quick2Static);
								J_Quick2Static.click();
							}
						}
					}
					ProcessUtil.ThreadSleep(1024);
					by = By.xpath("//input[@name='TPL_username']");
					user = driver.findElement(by);
					if (user != null) {
						WebDriverUtil.moveToElementAndClick(driver, by);
						user.clear();
						user.sendKeys(userName);
					}

					ProcessUtil.ThreadSleep(3000);
					by = By.xpath("//input[@name='TPL_password']");
					password = driver.findElement(by);
					if (password != null) {
						WebDriverUtil.moveToElementAndClick(driver, by);
						password.clear();
						password.sendKeys(userPass);
					}
					ProcessUtil.ThreadSleep(800);
					by = By.id("J_SubmitStatic");
					submit = driver.findElement(by);
					if (submit != null) {
						WebDriverUtil.moveToElementAndClick(driver, by);
					}
					ProcessUtil.ThreadSleep(500);

					sleepMs += 1000;
					LOG.info("还未登录成功,等待10000ms --" + driver.getCurrentUrl());
					ProcessUtil.ThreadSleep(10000);
					// 等待人工登录干预
					if (sleepMs == 1000 * 60 * 3) {
						String msg = shopName + "--淘宝登陆不成功,需要人工干预--" + driver.getCurrentUrl();
						LOG.info(msg);
						if (!sendErr) {
							SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
						}
					}
					if (sleepMs >= maxWaitTime) {
						String msg = shopName + "--淘宝登陆不成功,已等待" + maxWaitTime + "毫秒,退出运行 --" + driver.getCurrentUrl();
						LOG.info(msg);
						SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
						break;
					}
				} else {
					if (HttpUtil.getHost(driver.getCurrentUrl()).equals(HttpUtil.getHost(redirect_url))) {
						break;
					} else {
						driver.get(redirect_url);
						ProcessUtil.ThreadSleep(3000);
						// 如果仍然提示要登录
						if (driver.getCurrentUrl().contains("login.htm?forward=")) {
							driver.get(loginUrl);
							ProcessUtil.ThreadSleep(3000);
							continue;
						}
						if (HttpUtil.getHost(driver.getCurrentUrl()).equals(HttpUtil.getHost(redirect_url))) {
							break;
						}
					}
					break;
				}
			}
			LOG.info(shopName + "--登录成功--" + driver.getCurrentUrl());
			ProcessUtil.ThreadSleep(2000);
			cookieSet = driver.manage().getCookies();
			for (Cookie ck : cookieSet) {
				LOG.debug(ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure());
			}

		} catch (

		Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null) {
				driver.quit();
			}
		}
		return cookieSet;
	}

	/**
	 * 淘宝客页面_tb_token_值获取
	 * 
	 * @param cookie
	 * @return
	 */
	public static String getMyunionTbToken(String cookie) {
		String url = "http://ad.alimama.com/cps/shopkeeper/loginMessage.json";
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("Accept-Encoding", "gzip, deflate, br");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
		headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
		if (cookie == null || cookie.trim().equals("")) {
			headers.put("Cookie",
					"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
		} else {
			headers.put("Cookie", cookie);
		}
		headers.put("referer", "http://ad.alimama.com/myunion.htm");

		LinkedHashMap<String, String> parms = null;
		String webContent = HttpUtil.sendPostWithURLConnection(url, parms , headers);

		LOG.info(webContent);

		JSONObject retJson = JSONObject.fromObject(webContent);
		if (retJson.containsKey("data")) {
			if (retJson.getJSONObject("data").containsKey("_tb_token_")) {
				String _tb_token_ = retJson.getJSONObject("data").getString("_tb_token_");
				return _tb_token_;
			}
		}
		return null;
	}

	/**
	 * 淘宝客订单明细已结算数据获取,指定日期
	 * 
	 * @param cookie
	 * @param date
	 * @return
	 */
	public static JSONArray getMyunionTkTrans(String cookie, String date) {
		return getMyunionTkTrans(cookie, date, date);
	}

	/**
	 * 淘宝客订单明细已结算数据获取，所有页数据
	 * 
	 * @param cookie
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static JSONArray getMyunionTkTrans(String cookie, String startTime, String endTime) {
		JSONArray array = new JSONArray();
		//
		String token = TaobaoLoginAction.getMyunionTbToken(cookie);

		int pageSize = 50;
		int pageNo = 1;
		// 先抓取第一页
		JSONObject onePageJson = getMyunionTkTrans(cookie, token, startTime, endTime, pageNo, pageSize);
		// 获取总页数
		@SuppressWarnings("unused")
		int totalPages = 0;
		Boolean hasNext = false;
		if (onePageJson.containsKey("data") && onePageJson.getJSONObject("data").containsKey("totalPages")) {
			totalPages = onePageJson.getJSONObject("data").getInt("totalPages");
		}
		// 这里的总页数不准,改由hasNext来判断
		if (onePageJson.containsKey("data") && onePageJson.getJSONObject("data").containsKey("hasNext")) {
			hasNext = onePageJson.getJSONObject("data").getBoolean("hasNext");
		}
		// 添加第一页数据到array
		if (onePageJson.containsKey("data") && onePageJson.getJSONObject("data").containsKey("result")) {
			JSONArray tempArray = new JSONArray();
			tempArray = onePageJson.getJSONObject("data").getJSONArray("result");
			for (int j = 0; j < tempArray.size(); j++) {
				array.add(tempArray.get(j));
			}
			int thisPage = onePageJson.getJSONObject("data").getInt("pageNo");
			LOG.info("第" + thisPage + "页数据采集成功");
		}
		while (hasNext) {
			pageNo = pageNo + 1;
			onePageJson = getMyunionTkTrans(cookie, token, startTime, endTime, pageNo, pageSize);
			if (onePageJson.containsKey("data") && onePageJson.getJSONObject("data").containsKey("hasNext")) {
				hasNext = onePageJson.getJSONObject("data").getBoolean("hasNext");
			}
			// 添加后续页面数据到array
			if (onePageJson.containsKey("data") && onePageJson.getJSONObject("data").containsKey("result")) {
				JSONArray tempArray = new JSONArray();
				tempArray = onePageJson.getJSONObject("data").getJSONArray("result");
				for (int j = 0; j < tempArray.size(); j++) {
					array.add(tempArray.get(j));
				}
				int thisPage = onePageJson.getJSONObject("data").getInt("pageNo");
				LOG.info("第" + thisPage + "页数据采集成功/下一页:" + onePageJson.getJSONObject("data").getInt("nextPage") + "/" + onePageJson.getJSONObject("data").getBoolean("hasNext") + "/" + hasNext);
			}
		}
		return array;
	}

	/**
	 * 
	 * 淘宝客订单明细已结算数据获取，分页
	 * 
	 * @param cookie
	 * @param startTime
	 * @param endTime
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public static JSONObject getMyunionTkTrans(String cookie, String token, String startTime, String endTime, int pageNo, int pageSize) {
		String url = "http://ad.alimama.com/report/tkTrans.json";
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("Accept-Encoding", "gzip, deflate, br");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
		headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
		if (cookie == null || cookie.trim().equals("")) {
			headers.put("Cookie",
					"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
		} else {
			headers.put("Cookie", cookie);
		}
		headers.put("referer", "http://ad.alimama.com/myunion.htm");

		LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		params.put("pageNo", String.valueOf(pageNo));
		params.put("pageSize", String.valueOf(pageSize));
		params.put("status", "3");// 订单结算
		params.put("_tb_token_", token);
		String webContent = HttpUtil.sendPostWithURLConnection(url, params, headers);

		LOG.debug(webContent);

		JSONObject retJson = JSONObject.fromObject(webContent);
		if (retJson.containsKey("data")) {
			if (retJson.getJSONObject("data").containsKey("result")) {
				return retJson;
			} else {
				LOG.error(webContent);
			}
		} else {
			LOG.error(webContent);
		}
		return null;
	}

	
	
	/**生意参谋页面token值获取
	 * @param cookie
	 * @return
	 */
	public static String getSycmToken(String cookie) {

		String url = "https://sycm.taobao.com/portal/home.htm";
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		if (cookie == null || cookie.trim().equals("")) {
			headers.put("Cookie",
					"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
		} else {
			headers.put("Cookie", cookie);
		}
		headers.put("upgrade-insecure-requests", "1");
		String webContent = HttpUtil.sendGetWithURLConnection(url, null, headers);
		// LOG.info(webContent);
		String regex = "//meta[@name='microdata']";
		String tokenMetaContent = XsoupUtils.GetXsoupStr(webContent, regex);
		if (tokenMetaContent.contains("legalityToken")) {
			regex = "(?:legalityToken=)([\\s\\S]*)(?:\\;)";
			String token = RegUtil.GetRegStr(tokenMetaContent, regex, 1);
			if (!StringUtil.isBlank(token)) {
				return token;
			} else {
				LOG.info(tokenMetaContent);
			}
		}
		return null;
	}
	
	/**
	 * 生意参谋 热销商品榜
	 * @param cookie
	 * @param token
	 * @param date
	 * @return
	 */
	public static JSONArray getHotProducts(String cookie, String token, String date) {
		return getHotProducts(cookie, token, date,date);
	}
	
	/**
	 * 生意参谋 热销商品榜
	 * @param cookie
	 * @param token
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static JSONArray getHotProducts(String cookie, String token, String startTime,String endTime) {
		JSONArray array = new JSONArray();
		int pageSize = 15;
		int pageNo = 1;
		// 先抓取第一页
		JSONObject onePageJson = getHotProducts(cookie, token, startTime, endTime, pageNo, pageSize);
		// 获取总页数
		int totalPages = 0;
		int recordCount = 0;
		if (onePageJson.containsKey("content") && onePageJson.getJSONObject("content").containsKey("data") && onePageJson.getJSONObject("content").getJSONObject("data").containsKey("recordCount")) {
			recordCount = onePageJson.getJSONObject("content").getJSONObject("data").getInt("recordCount");
		}
		//计算总页数
		totalPages = recordCount/pageSize + 1;
		// 添加第一页数据到array
		if (onePageJson.containsKey("content") && onePageJson.getJSONObject("content").containsKey("data") && onePageJson.getJSONObject("content").getJSONObject("data").containsKey("data")) {
			JSONArray tempArray = new JSONArray();
			tempArray = onePageJson.getJSONObject("content").getJSONObject("data").getJSONArray("data");
			for (int j = 0; j < tempArray.size(); j++) {
				array.add(tempArray.get(j));
			}
			LOG.info("第" + pageNo + "页数据采集成功");
		}
		for(int i = 2;i<=totalPages;i++){
			pageNo = pageNo + 1;
			onePageJson = getHotProducts(cookie, token, startTime, endTime, pageNo, pageSize);
			// 添加后续页面数据到array
			if (onePageJson.containsKey("content") && onePageJson.getJSONObject("content").containsKey("data") && onePageJson.getJSONObject("content").getJSONObject("data").containsKey("data")) {
				JSONArray tempArray = new JSONArray();
				tempArray = onePageJson.getJSONObject("content").getJSONObject("data").getJSONArray("data");
				for (int j = 0; j < tempArray.size(); j++) {
					array.add(tempArray.get(j));
				}
				LOG.info("第" + pageNo + "页数据采集成功");
			}
		}
		return array;
		
	}
	
	/**
	 * 生意参谋 热销商品榜
	 * @param cookie
	 * @param token
	 * @param startTime
	 * @param endTime
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public static JSONObject getHotProducts(String cookie, String token, String startTime, String endTime, int page, int pageSize) {

		String url = "https://sycm.taobao.com/mq/rank/listItems.json";
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
		headers.put("Accept", "*/*");
		if (cookie == null || cookie.trim().equals("")) {
			headers.put("Cookie",
					"thw=cn; UM_distinctid=15ac59b61b613d-0db6a7357e4f9a-64191279-e1500-15ac59b61b71a7; miid=940406189146175580; _tb_token_=7487e53163d15; CNZZDATA1000005116=79458772-1490085544-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490142466; CNZZDATA1000005141=2117037845-1490083057-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490144209; CNZZDATA1000005138=558639850-1490082712-https%253A%252F%252Fsubway.simba.taobao.com%252F%7C1490147417; x=595397331; uc3=sg2=ACywOWsALw1aR6kc9lJhSSqrUOj1NJ36VUEkmbNggrc%3D&nk2=&id2=&lg2=; uss=U7PGB4MB5pDlL2OCcDPRo31nJKpV5%2Bc2hFryXRjLmqXfReVyJgEDI8cpJmA%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; skt=dd4a58495e2d1aa0; v=0; cookie2=1d6f3955769cb579f21e96a7e2c1ee90; unb=2965098721; t=12701f1960bc1fa73cc07ee19f76d148; JSESSIONID=DE40B88DAC13088A159D4D8520F4D73F; uc1=cookie14=UoW%2BuKEucRVgaQ%3D%3D&lng=zh_CN; cna=DAcLES61/V8CAT23zfVk6dgh; l=Anl5Fvkd9H6ZZMW2Pj69AWa4Ce9TC20-; isg=AtLSiBYI3rzRPSJXzaWL33O-I5g7pfS7TK3_wZwrcwV2r3KphHMmjdiJabxp");
		} else {
			headers.put("Cookie", cookie);
		}
		headers.put("referer", "https://sycm.taobao.com/mq/industry/rank/industry.htm");

		LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
		params.put("cateId", "50018222");// DIY电脑
		params.put("categoryId", "50018222");// DIY电脑
		params.put("dateRange", startTime + "|" + endTime);
		params.put("dateRangePre", startTime + "|" + endTime);
		params.put("dateType", "day");
		params.put("dateTypePre", "day");
		params.put("device", "0");
		params.put("devicePre", "0");
		params.put("itemDetailType", "1");
		params.put("keyword", "");
		params.put("orderDirection", "desc");
		params.put("orderField", "payOrdCnt");
		params.put("page", String.valueOf(page));
		params.put("pageSize", String.valueOf(pageSize));
		params.put("rankTabIndex", "0");
		params.put("rankType", "1");
		params.put("seller", "-1");
		params.put("token", token);
		params.put("view", "rank");
		long t = DateUtil.getUnixTime();
		params.put("_", String.valueOf(t));
		String webContent = HttpUtil.sendGetWithURLConnection(url, params, headers);

		LOG.debug(webContent);

		JSONObject retJson = JSONObject.fromObject(webContent);
		if (retJson.containsKey("content")) {
			if (retJson.getJSONObject("content").containsKey("data")) {
				return retJson;
			} else {
				LOG.error(webContent);
			}
		} else {
			LOG.error(webContent);
		}
		return null;
	}

	/** ------------以下方法未使用------------- */
	public static Set<Cookie> getAlimamaLoginCookieByFirefox(String shopName, String loginUrl, String userName, String userPass) {
		Set<Cookie> cookieSet = null;
		WebDriver driver = null;
		try {
			driver = DriverFactory.getGeckoDriver();
			driver.get(loginUrl);
			ProcessUtil.ThreadSleep(10000000);

		} catch (

		Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null) {
				driver.quit();
			}
		}
		return cookieSet;

	}
}
